# -*- coding:utf-8 -*-
"""
装饰器
"""
__author__ = "shu2015626"

from functools import wraps
from collections import Iterable

from django.core import serializers

from users.models import UserOperationLog


def log_oper_decorator(cls):
    """
    admin.ModelAdmin的装饰器
    用来记录用户进行的指定的操作
    :param cls:
    :return:
    """
    function_list = ["delete_model", "save_model", "delete_queryset"]

    def add_logger(func):
        @wraps(func)
        def wrapper(modeladmin, request, obj, *args, **kwargs):
            if isinstance(obj, Iterable):
                json_data = serializers.serialize('json', obj)
            else:
                json_data = serializers.serialize('json', [obj])
            obj_user_operation = UserOperationLog(
                user=request.user,
                operation=func.__name__,
                resource=request.path,
                content=json_data
            )
            obj_user_operation.save()
            return func(modeladmin, request, obj, *args, **kwargs)
        return wrapper

    for function in function_list:
        cls_func = getattr(cls, function, None)
        if cls_func is not None:
            setattr(cls, function, add_logger(cls_func))
    return cls
